<?php
defined ( 'IN_SYS' ) or die ( 'Restricted Access' );
class Page {
	// Luu tru cac bien duoc REQUEST tren PAGE
  	private static $config = array();
  	public static $is_header = true; // true|false: input header
  	public static $lang = array();
  	
  	public static $title = '';
  	public static $spec = '';
  	public static $inc_require_js_css = array('header' => array('js'=>array(), 'css'=>array()),
  										'footer' => array('js'=>array(), 'css'=>array()));
  	public static $inc_require_meta = array('header'=>array(), 'footer'=>array());
  	//public static $inc_header = array('js'=>array(), 'css'=>array());
  	//public static $inc_footer = array('js'=>array(), 'css'=>array());
  	
  	public static $header = array('status'=> '200', 'params'=>array());
  	public static $__SESSIONS__ = array();	// Session of Page
  	
  	public static $page_info = array();	// push page-info
  	
  	public static $page_param = array();	
	/**
	 * Retrieve a config parameter.
	 *
	 * @param string A config parameter name.
	 * @param mixed  A default config parameter value.
	 *
	 * @return mixed A config parameter value, if the config parameter exists, otherwise null.
	 */
	public static function get ($name, $default = null){
    	return isset(self::$config[$name]) ? self::$config[$name] : $default;
	}

  /**
   * Set a config parameter.
   *
   * If a config parameter with the name already exists the value will be overridden.
   *
   * @param string A config parameter name.
   * @param mixed  A config parameter value.
   *
   * @return void
   */
  	public static function set ($name, $value){
    	self::$config[$name] = $value;
  	}

  /**
   * Set an array of config parameters.
   *
   * If an existing config parameter name matches any of the keys in the supplied
   * array, the associated value will be overridden.
   *
   * @param array An associative array of config parameters and their associated values.
   *
   * @return void
   */
  	public static function add ($parameters = array()){
    	self::$config = array_merge(self::$config, $parameters);
  	}
  	
  	/**
  	 * Check parameter is exists
  	 * @param string $name
  	 * @return true|false
  	 */
  	public static function has ($name){
  		return isset(self::$config[$name]);
  	}

  	/**
     * Retrieve all configuration parameters.
     *
     * @return array An associative array of configuration parameters.
     */
  	public static function getAll (){
    	return self::$config;
  	}

  /**
   * Clear all current config parameters.
   *
   * @return void
   */
  	public static function clear (){
    	self::$config = array();
  	}
  	
  	/**
     * Set a config parameter.
     *
     * If a config parameter with the name already exists the value will be overridden.
     *
     * @param string A config parameter name.
     * @param mixed  A config parameter value.
     *
     * @return void
     */
  	public static function push($name=NULL, $value=NULL){
  		if (isset(self::$config[$name]) AND is_array(self::$config[$name])){
  			array_push(self::$config[$name], $value);
  		} else {
  			self::$config[$name] = array();
  			array_push(self::$config[$name], $value);
  		}
  	}
  	
  	
  	/**
  	 * @desc register the file css/js to PAGE
  	 * @param string $property = css/js
  	 * @param string $path real Path file
  	 * @param string $position: header/footer
  	 * @param string $ext Extention
  	 * @return String <link stylesheet... /> OR <script javascript... /> 
  	 */
  	public static function reg($property='js', $path='', $position='header', $ext=''){
  		if ($property != 'css' && $property != 'js') return;
  		if ($position != 'header' && $position != 'footer') return;
  		
  		$path = SYS_SKINS . $path;
  			
  		if (STATIC_IS_INCLUDE) { // if STATIC_IS_INCLUDE = TRUE
  			$str = $path;
  		} else {
  			if ($property == 'css') {
	  			$str = '<link rel="stylesheet" type="text/css" href="'.$path.'" charset="utf-8" '.$ext.'/>';
	  		}
	  		else {
	  			$str = '<script type="text/javascript" src="'.$path.'" charset="utf-8" '.$ext.'></script>';
	  		}
  		}
	  	
		if (!isset(self::$inc_header[$property]) || !is_array(self::$inc_header[$property])) {
			self::$inc_header[$property] = array();
		}
		if (!isset(self::$inc_footer[$property]) || !is_array(self::$inc_footer[$property])) {
			self::$inc_footer[$property] = array();
		}
		
		if ($position == 'header' && !in_array($path, self::$inc_header[$property])) {
			self::$inc_header[$property][$path] = $str;
		}
		if ($position == 'footer' && !in_array($path, self::$inc_footer[$property])) {
			self::$inc_footer[$property][$path] = $str;
		}
  	}
  	
  	/**
  	 * register in header or footer on the PAGE
  	 */
  	public static function regExt($property='js', $ext='', $position='header') {
  		if ($position == 'header' && !in_array($ext, self::$inc_header[$property]))
  			self::$inc_header[$property][$ext] = $ext;
  		if ($position == 'footer' && !in_array($ext, self::$inc_footer))
  			self::$inc_footer[$property][$ext] = $ext;
  	}
  	
  	////////////////////////////////////////////////////////////////////////////////
  	// REQUEST DATA
  	/**
  	 * return value of parameter from: form, url, cookie, session,...
  	 * @param $name
  	 * @param $validate
  	 * @param $def_value
  	 * @param $method: GET,POST,REQUEST,FILE,COOKIE,SESSION,SERVER,GLOBAL
  	 */
  	public static function getRequest($name='', $validate='def', $def_value=NULL, $method='REQUEST'){
		switch ($method){
			case 'GET':
				$value = isset($_GET[$name])?$_GET[$name]:NULL;
				break;
			case 'POST':
				$value = isset($_POST[$name])?$_POST[$name]:NULL;
				break;
			case 'REQUEST':
				$value = isset($_REQUEST[$name])?$_REQUEST[$name]:NULL;
				break;
			case 'FILE':
				$value = isset($_FILE[$name])?$_FILE[$name]:NULL;
				break;
			case 'COOKIE':
				$value = isset($_COOKIE[$name])?$_COOKIE[$name]:NULL;
				break;
			case 'SESSION':
				$value = isset($_SESSION[$name])?$_SESSION[$name]:NULL;
				break;
			case 'SERVER':
				$value = isset($_SERVER[$name])?$_SERVER[$name]:NULL;
				break;
			case 'GLOBAL':
				$value = isset($_GLOBAL[$name])?$_GLOBAL[$name]:NULL;
				break;
			default :
				$value = isset($_REQUEST[$name])?$_REQUEST[$name]:NULL;
				break;
		}
		
		// debug get value
		if (IS_DEBUG) {
			$value = isset($_REQUEST[$name])?$_REQUEST[$name]:NULL;
		}
		
		// add by HoangNV2 at 2012/05/23 for DEBUG
		if (IS_MAGIC_QUOTES && !is_null($value) && !is_array($value)) {
			$value = stripcslashes($value);
		}
		
		// add by HoangNV2 at 2012/05/23 for DEBUG
		$_tmp = array($method => $name, 'value' => $value, 'validate' => $validate);
		
		if (is_null($value)) {
			// add by HoangNV2 at 2012/05/23 for DEBUG
			$_tmp['return'] = $value;
			self::$page_param[] = $_tmp;
			return $def_value;
		}
		
		elseif ($validate == 'int'){
			(int) $value;
		}
		
		elseif ($validate == 'str'){
			(string) $value;
		}
		/*if ($validate == 'def'){
			$value;
		}*/
		
		// add by HoangNV2 at 2012/05/23 for DEBUG
		$_tmp['return'] = $value;
		self::$page_param[] = $_tmp;
		
		return $value;
  	}
  	
  	public static function hasRequest($name, $method='REQUEST') {
  		switch ($method){
			case 'GET':
				return isset($_GET[$name]);
				break;
			case 'POST':
				return isset($_POST[$name]);
				break;
			case 'REQUEST':
				return isset($_REQUEST[$name]);
				break;
			case 'FILE':
				return isset($_FILES[$name]);
				break;
			case 'COOKIE':
				return isset($_COOKIE[$name]);
				break;
			case 'SESSION':
				return isset($_SESSION[$name]);
				break;
			case 'SERVER':
				return isset($_SERVER[$name]);
				break;
			case 'GLOBAL':
				return isset($_GLOBAL[$name]);
				break;
			default :
				return isset($_REQUEST[$name]);
				break;
		}
		return false;
  	}
  	
	/**
	 * @desc Tra ve data of method
	 * @param string $method : POST, GET, REQUEST, FILE, COOKIE, SESSION, SERVER
	 */
	public static function getRequestAll($method=null){
		if (!$method) return NULL;
		
		switch ($method){
			case 'POST':
				$_param = $_POST;
				break;
			case 'GET':
				$_param = $_GET;
				break;
			case 'REQUEST':
				$_param = $_REQUEST;
				break;
			case 'FILE':
				$_param = $_FILES;
				break;
			case 'COOKIE':
				$_param = $_COOKIE;
				break;
			case 'SESSION':
				$_param = $_SESSION;
				break;
			case 'SERVER':
				$_param = $_SERVER;
				break;
			default :
				$_param = $_REQUEST;
				break;
		}
		
		return $_param;
	}
	
	
	public static function printHeader() {
		if (!self::$is_header) return;
		require_once SYS_LIB_KERNEL . 'sys.minify.php';
		$objMinify = new SysMinify();
		
		$html = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
					<html>
					<head>
					<meta http-equiv="Content-Type" content="text/html; charset='.SYS_CHARSET.'">';
		$html.= '<title>'.self::getTitle().'</title>';
		if (STATIC_COMPRESS_TPL === TRUE) {
			$html = $objMinify->compress_html($html);
		}
		
		$html.= "\n";
		
		if (!isset(self::$inc_header['css'])) {
			self::$inc_header['css'] = array();
		}
		
		if (!isset(self::$inc_header['js'])) {
			self::$inc_header['js'] = array();
		}
		
		if (isset(self::$inc_header['css']) && !empty(self::$inc_header['css'])) {
			if (!STATIC_IS_INCLUDE) { // if STATIC_IS_INCLUDE = flase
				foreach (self::$inc_header['css'] as $rs) {
					$html.= $rs."\n";
				}
			} else {
				$html.= "<style type=\"text/css\">\n";
				foreach (self::$inc_header['css'] as $rs) {
					$content = $objMinify->getContentFile($rs);
					if (STATIC_FILE_COMPRESS_CSS && substr($rs, 0, -strlen('.min.css')) != '.min.css') {
						$content = $objMinify->compress_css($content);
					}
					$html.= $content."\n";
				}
				$html.= "</style>\n";
			}
		}
		
		if (isset(self::$inc_header['js']) && !empty(self::$inc_header['js'])) {
			if (!STATIC_IS_INCLUDE) { // if STATIC_IS_INCLUDE = flase
				foreach (self::$inc_header['js'] as $rs) {
					$html.= $rs."\n";
				}
			} else {
				$html.= "<script type=\"text/javascript\">\n<!---\n";
				foreach (self::$inc_header['js'] as $rs) {
					$content = $objMinify->getContentFile($rs);
					if (STATIC_FILE_COMPRESS_JS && substr($rs, -strlen('.min.js')) != '.min.js') {
						$content = $objMinify->compress_js($content);
					}
					$html.= $content.";\n";
				}
				$html.= "// --->\n</script>\n";
			}
		}
		
		$html.= '</head>';
		return $html;
	}
	
	public static function printFooter() {
		if (!self::$is_header) return;
		
		require_once SYS_LIB_KERNEL . 'sys.minify.php';
		$objMinify = new SysMinify();
		
		if (!isset(self::$inc_footer['css'])) {
			self::$inc_footer['css'] = array();
		}
	
		if (!isset(self::$inc_footer['js'])) {
			self::$inc_footer['js'] = array();
		}
		
		$html = '';
		if (isset(self::$inc_footer['css']) && !empty(self::$inc_footer['css'])) {
			if (!STATIC_IS_INCLUDE) { // if STATIC_IS_INCLUDE = flase
				foreach (self::$inc_footer['css'] as $rs) {
					$html.= $rs."\n";
				}
			} else {
				$html.= "<style type=\"text/css\">\n";
				foreach (self::$inc_footer['css'] as $rs) {
					$content = $objMinify->getContentFile($rs);
					if (STATIC_COMPRESS_CSS && substr($rs, 0, -strlen('.min.css')) != '.min.css') {
						$content = $objMinify->compress_css($content);
					}
					$html.= $content."\n";
				}
				$html.= "</style>\n";
			}
		}
		
		if (isset(self::$inc_footer['js']) && !empty(self::$inc_footer['js'])) {
			if (!STATIC_IS_INCLUDE) { // if STATIC_IS_INCLUDE = flase
				foreach (self::$inc_footer['js'] as $rs) {
					$html.= $rs."\n";
				}
			} else {
				$html.= "<script type=\"text/javascript\">\n<!---\n";
				foreach (self::$inc_footer['js'] as $rs) {
					$content = $objMinify->getContentFile($rs);
					if (STATIC_COMPRESS_JS && substr($rs, -strlen('.min.js')) != '.min.js') {
						$content = $objMinify->compress_js($content);
					}
					$html.= $content.";\n";
				}
				$html.= "// --->\n</script>\n";
			}
		}
		
		return $html;
	}
	/**
	 * clear
	 */
	public static function clearReg() {
		self::$inc_header = array('js'=>array(), 'css'=>array());
		self::$inc_footer = array('js'=>array(), 'css'=>array());
	}
	
  	
  	/**
  	 * @desc Filter request data
  	 * @desc Protects better diverse attempts of Cross-Site Scripting attacks
  	 * @desc Security INPUT
  	 */
  	public static function filterRequest(){
  		/*// Cross-Site Scripting attack defense 
		// Lets now sanitize the GET vars
	    if (count($_GET) > 0) {
        	foreach ($_GET as $secvalue) {
        		if (!is_array($secvalue)) {
					if ((eregi("<[^>]*script.*\"?[^>]*>", $secvalue)) ||
							(eregi(".*[[:space:]](or|and)[[:space:]].*(=|like).*", $secvalue)) ||
							(eregi("<[^>]*object.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*iframe.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*applet.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*meta.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*style.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*form.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*window.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*alert.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*img.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*document.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*cookie.*\"?[^>]*>", $secvalue)) ||
							(eregi("\"", $secvalue))) {
							Header("Location: index.php");
					}
				}
			}
		}
	
		// Lets now sanitize the POST vars
		if ( count($_POST) > 0) {
			foreach ($_POST as $secvalue) {
				if (!is_array($secvalue)) {
					if ((eregi("<[^>]*script.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*object.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*iframe.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*applet.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*window.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*alert.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*document.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*cookie.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*meta.*\"?[^>]*>", $secvalue))
							) {
							Header("Location: index.php");
					}
				}
			}
		}
	
		//Lets now sanitize the COOKIE vars
		if ( count($_COOKIE) > 0) {
			foreach ($_COOKIE as $secvalue) {
				if (!is_array($secvalue)) {
					if ((eregi("<[^>]*script.*\"?[^>]*>", $secvalue)) ||
							(eregi(".*[[:space:]](or|and)[[:space:]].*(=|like).*", $secvalue)) ||
							(eregi("<[^>]*object.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*iframe.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*applet.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*meta.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*style.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*form.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*window.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*alert.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*document.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*cookie.*\"?[^>]*>", $secvalue)) ||
							(eregi("<[^>]*img.*\"?[^>]*>", $secvalue))
							) {
							Header("Location: index.php");
					}
				}
			}
		}*/
  	}

	/**
	 * @desc create URL on system
	 */
	public static function goUrl ($param=array(),$page=NULL,$portal=NULL) {
		if (is_null($portal)) $portal = Page::get('SYS_PORTAL');
		if (is_null($page)) $page = Page::get('SYS_PAGE');
		$url = SYS_URL_SCRIPT 
				. '?portal='. $portal
				. '&page='. $page;
		
		if (is_array($param) && !empty($param)) {
			foreach ($param as $key=>$val) {
				$url.= '&'.urlencode($key).'='.urlencode($val);
			}
		}
		return $url;
	}

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	// SESSION
	/**
	 * set session
	 */
	public static function setSession($name='',$value=NULL) {
		if (SYS_IS_CLOUD) {
			self::$__SESSIONS__[$name] = $value;
		}
		
		$_SESSION[$name] = $value;
	}
	
	/**
	 * get session
	 */
	public static function getSession($name='') {
		if (SYS_IS_CLOUD) {
			if (isset(self::$__SESSIONS__[$name])) return self::$__SESSIONS__[$name];
		} else {
			if (isset($_SESSION[$name])) return $_SESSION[$name];
		}
		
		return NULL;
	}
	
	/**
	 * remove session
	 */
	public static function removeSession($name='') {
		if (isset(self::$__SESSIONS__[$name]) || isset($_SESSION[$name])) {
			$_SESSION[$name] = NULL;
			unset($_SESSION[$name]);
			
			self::$__SESSIONS__[$name] = NULL;
			unset(self::$__SESSIONS__[$name]);
			
			return true;
		}
		
		return false;
	}
	
	/**
	 * has session
	 */
	public static function hasSession($name='') {
		if (SYS_IS_CLOUD) {
			return isset(self::$__SESSIONS__[$name]);
		} else {
			return isset($_SESSION[$name]);
		}
	}
	
	/**
	 * get session
	 */
	public static function getSessionAll() {
		if (SYS_IS_CLOUD) {
			if (isset(self::$__SESSIONS__)) return self::$__SESSIONS__;
		} else {
			if (isset($_SESSION)) return $_SESSION;
		}
		
		return NULL;
	}
	
	/**
	 * clear all session
	 */
	public static function clearSession() {
		self::$__SESSIONS__ = array();
		$_SESSION = array();
	}
	
	/**
	 * encode sesion
	 */
	public static function encodeSession () {
		if (SYS_IS_CLOUD) {
			$str = json_encode(self::$__SESSIONS__);
			$str = base64_encode($str);
		} else {
			$str = json_encode($_SESSION);
			$str = base64_encode($str);
		}
		
		return $str;
	}
	
	/**
	 * decode sesion
	 */
	public static function decodeSession () {
		if (SYS_IS_CLOUD) {	// if use no session of system
			if (empty(self::$__SESSIONS__)) {
				$str = Page::getRequest(SYS_SESSION_NAME, 'def', '', 'POST');
				$str = base64_decode($str);
				self::$__SESSIONS__ = json_decode($str, true);
				
				foreach ($_SESSION as $key=>$val) {
					if (!isset(self::$__SESSIONS__[$key])) {
						self::$__SESSIONS__[$key] = $val;
					}
				}
			}
			$_SESSION = self::$__SESSIONS__;
		} else {
			self::$__SESSIONS__ = $_SESSION;
		}
		
		return self::$__SESSIONS__;
	}
	// End SESSION
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	
	/**
	 * Header URL
	 */
	public static function goReferer($param=array(), $page='', $portal='') {
		$url = self::goUrl($param, $page, $portal);
		ob_start();
		Header("Location: ".$url);
		ob_end_flush();
		exit();
	}
	
	/**
	 * setHeader
	 * @param int $status
	 * @param array() $parameter
	 */
	public static function setHeader($status='200', $params=array()) {
		self::$header['status'] = $status;
		self::$header['params'] = $params;
	}
	
	/**
	 * setTitle()
	 * @param $title name
	 */
	public static function setTitle($title='') {
		self::$title = $title;
	}
	
	public static function getTitle() {
		return self::$title;
	}
	
	
	/**
	 * setSpec
	 * @param $name
	 */
	public static function setSpec($name='') {
		self::$spec = $name;
		Page::setSession('ScreenId', $name);
	}
	
	public static function getSpec() {
		return self::$spec;
	}
	
	/**
     * @desc get languages file of template
     */
    static function getLangsPublic () {
    	$path_public = SYS_APPS_VIEWER . 'languages'. DS . SYS_LANG_DEFAULT . DS . 'langs.php';
    	if (file_exists($path_public)) {
    		self::$lang += include($path_public);
    	}
    	
    	return self::$lang;
    }
    
    /**
     * @desc get languages file of template
     */
    static function getLangsPrivate($portal, $file) {
    	$path_private = SYS_APPS_VIEWER . 'languages'. DS . SYS_LANG_DEFAULT . DS . $portal . DS . 'lang.' . $file . '.php';
    	if (file_exists($path_private)) {
    		self::$lang += include($path_private);
    	}
    	
    	return self::$lang;
    }
    
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    static function pushInfoPage ($spec, $action, $tpl) {
    	array_push(self::$page_info, array('SPEC'=>$spec, 'ACTION'=>$action, 'TEMPLATE'=>$tpl));
    }
    
    static function getInfoPage () {
    	return array_reverse(self::$page_info);
    }
}